library(RColorBrewer)
library(ggrepel)
library(lubridate)
library(scales)
library(tidyverse)

cpi_index <- as_tibble(cpi_score_2005_2015) 
cpi_index <- cpi_index %>%
  select(year, country, cpi_score, rec) %>%
  mutate(year = make_date(year))
cpi_index$year <- as.Date(cpi_index$year)

### ECOWAS ###
ecowas_mean <- na.omit(cpi_index) %>%
  filter(country != "Mali", rec == "ECOWAS") %>%
  group_by(year) %>%
  summarise_at(vars(cpi_score), 
  list(mean = mean))

mean(ecowas_mean$mean) # ECOWAS Mean = 2.8

# Mali mean = 2.9
na.omit(cpi_index) %>%
  filter(country == "Mali") %>%
  summarise_at(vars(cpi_score),
               list(mean = mean))

### ECCAS ### 
eccas_mean <- na.omit(cpi_index) %>%
  filter(country != "CAR", rec == "ECCAS") %>%
  group_by(year) %>%
  summarise_at(vars(cpi_score), 
               list(mean = mean))

mean(eccas_mean$mean) # ECCAS Mean = 2.4

eccas_median <- na.omit(cpi_index) %>%
  filter(country != "CAR", rec == "ECCAS") %>%
  group_by(year) %>%
  summarise_at(vars(cpi_score), 
               list(median = median))

median(eccas_median$median) # ECCAS median = 2.2

# CAR mean = 2.2
na.omit(cpi_index) %>%
  filter(country == "CAR") %>%
  summarise_at(vars(cpi_score),
               list(mean = mean))

na.omit(cpi_index) %>%
  filter(rec == "ECCAS") %>%
  group_by(country) %>%
  ggplot(aes(year, cpi_score, color = country), size = 2) +
  geom_line(stat = "identity") +
  theme_bw()

# Boxplot for ECCAS 
na.omit(cpi_index) %>%
  filter(rec == "ECCAS") %>%
  group_by(country) %>%
  ggplot(aes(year, cpi_score, color = country), size = 2) +
  geom_boxplot() +
  theme_bw()
# Rwanda's CPI score skews the average in ECCAS. Better to use the median. 

# pull out cpi scores for Mali and CAR
car_score <- (cpi_index) %>%
  filter(country == "CAR")

mali_score <- na.omit(cpi_index) %>%
  filter(country == "Mali")

# Plot for comparison
na.omit(cpi_index) %>%
  group_by(country) %>%
  ggplot(aes(year, cpi_score, color = country), size = 2) +
  geom_line(stat = "identity") +
  theme_bw() +
  xlab("Year") + ylab("Corruption Perception Score") + 
  labs(title = "Sub-Saharan Africa Corruption Perceptions, 2005-2015", 
       subtitle = "Comparison of ECOWAS and ECCAS countries on corruption",
       caption = "Source: Corruption Perception Index (Transparency International)",
       color = "Country")
  
# Mean/Median values by year for ECOWAS and ECCAS
ecowas_eccas_sum_stats <- na.omit(cpi_index) %>%
  filter(country != c("Mali", "CAR")) %>%
  group_by(year, rec) %>%
  summarise(mean_v = mean(cpi_score),
            median_v = median(cpi_score),
            min_v = min(cpi_score),
            max_v = max(cpi_score))
# create labels for plot
labels <- c(ECCAS = "Economic Community of Central African States (ECCAS)", 
            ECOWAS= "Economic Community of West African States (ECOWAS)")
state_label <- data.frame(x1 = c(as.Date("2010-01-01"), as.Date("2010-01-01")),
                          y1 = c(2.6, 3.25), lab = c("CAR", "Mali"),
                          rec = c("ECCAS", "ECOWAS")) 
seg_label <- data.frame(x1 = c(as.Date("2010-01-01"), as.Date("2010-01-01")),
                        x2 = c(as.Date("2010-06-01"), as.Date("2010-05-01")),
                        rec = c("ECCAS", "ECOWAS"),
                        y1 = c(2.5, 3.15), 
                        y2 = c(2.2, 2.8))
median_label <- data.frame(x1 = c(as.Date("2012-10-01"), as.Date("2008-09-01")),
                                          y1 = c(1.67, 2.3), lab = c("ECCAS \n Median", "ECOWAS \n Median"),
                                          rec = c("ECCAS", "ECOWAS")) 
medseg_label <- data.frame(x1 = c(as.Date("2012-10-01"), as.Date("2008-08-01")),
                        x2 = c(as.Date("2012-05-01"), as.Date("2008-08-01")),
                        rec = c("ECCAS", "ECOWAS"),
                        y1 = c(1.85, 2.47), 
                        y2 = c(2.18, 2.78))
min_label <- data.frame(x1 = c(as.Date("2005-01-01"), as.Date("2005-01-01")),
                           y1 = c(1.5, 1.7), lab = c("Min", "Min"),
                           rec = c("ECCAS", "ECOWAS"))  
max_label <- data.frame(x1 = c(as.Date("2005-01-01"), as.Date("2005-01-01")),
                        y1 = c(3.3, 3.7), lab = c("Max", "Max"),
                        rec = c("ECCAS", "ECOWAS"))  
outlier_label <- data.frame(x1 = c(as.Date("2009-06-01"), as.Date("2010-04-01")),
                          y1 = c(4.6, 4.6), lab = c("Rwanda", "Ghana"),
                          rec = c("ECCAS", "ECOWAS")) 
outlier_tick <- data.frame(x1 = c(as.Date("2009-06-01"), as.Date("2010-06-01")),
                           x2 = c(as.Date("2010-01-01"), as.Date("2011-04-01")),
                           rec = c("ECCAS", "ECOWAS"),
                           y1 = c(4.5, 4.5), 
                           y2 = c(4.18, 4.2))

# Plot CPI comparison
cpi_plot <- na.omit(ecowas_eccas_sum_stats) %>%
  ggplot(aes(year, median_v, color = rec)) +
  geom_line(linetype = "dashed") +
  geom_line(data = mali_score, aes(x = year, 
                                   y = cpi_score), size=1.25, show.legend = F) +
  geom_line(data = car_score, aes(x = year, 
                                  y = cpi_score), size=1.25, show.legend = F) +
  geom_ribbon(aes(ymin = min_v, ymax = max_v, fill = rec),
              alpha = 0.3, show.legend = F) +
  scale_color_brewer(palette = "Dark2", name = "Country", labels = c("CAR", "Mali")) +
  scale_fill_brewer(palette = "Dark2", name = "Region", labels = c("Central", "West")) +
  facet_grid(cols = vars(rec), labeller = labeller(rec = labels)) +
  theme_bw() +
  theme_fivethirtyeight() +
  xlab("Calendar Year") + ylab("Corruption Perception Score (0-10)") + 
  labs(title = "Figure 1: Sub-Saharan Africa Corruption Perceptions", 
       subtitle = "Comparison of Mali and the Central African Republic with regional member states, 2005-2015.",
       caption = " Scores are scaled from 0.0 (highly corrupt) to 10.0 (very clean).
       Source: Corruption Perception Index (Transparency International).",
       color = "Country")

# Annotate Labels 
cpi_plot <- cpi_plot +
  geom_text(data = state_label, aes(x = x1, y = y1, label = lab, fontface = "bold"), color = "gray12") +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), color = "gray12", data = seg_label) +
  geom_text(data = median_label, aes(x = x1, y = y1, label = lab, fontface = "bold"), size = 3.3, color = "#666666") +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), color = "#666666", data = medseg_label) +
  geom_text(data = min_label, aes(x = x1, y = y1, label = lab, fontface = "italic"), size = 3, color = "#666666") +
  geom_text(data = max_label, aes(x = x1, y = y1, label = lab, fontface = "italic"), size = 3, color = "#666666") +
  geom_text(data = outlier_label, aes(x = x1, y = y1, label = lab, fontface = "bold"), color = "#666666") +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), color = "#666666", data = outlier_tick) +
  theme(legend.position = "none") 

# Print plot
plot(cpi_plot)

######## Fig. 2 Militarization Plot #########
aid_data <- as_tibble(us_military_aid)

# filter obligations by DOD and DOS security assistance
aid_data <- aid_data %>%
  select(fiscal_year, country_name, implementing_agency_name, implementing_agency_acronym, 
         funding_agency_name, funding_agency_acronym, assistance_category_name, constant_amount) %>%
  mutate(fiscal_year = make_date(fiscal_year)) %>%
  filter(assistance_category_name == "Military", implementing_agency_acronym == c("STATE", "DOD"))

aid_data$constant_amount <- as.integer(aid_data$constant_amount)

aid_data %>%
  select(fiscal_year, constant_amount) %>%
  summarise(mean(constant_amount))

# plot graph of security assistance
 aid_plot <- ggplot(data = aid_data, aes(fiscal_year, constant_amount)) +
  geom_col(aes(fill = funding_agency_name), alpha = 0.9) +
    scale_y_continuous(labels = dollar_format(scale = .000001, suffix = "M")) +
  scale_fill_manual(values = c("#4f7942", "#041e42"), name = "") +
  theme_fivethirtyeight() +
  xlab("Calendar Year") + ylab("Total Funds Obligated") + 
  labs(title = "Figure 2: U.S. Security Assistance in Africa", 
       subtitle = "Comparison of DoS and DoD funding obligations, FY 2005-2018",
       caption =  "Source: Foreign Aid Explorer, USAID.") 
 
 # annotate plot 
 seg_tick <- data.frame(x1 = as.Date("2009-01-01"), 
            x2 = as.Date("2009-01-01"),
            y1 = 0,
            y2 = 465000000)
 africom_label <- data.frame(x1 = as.Date("2010-03-01"), y1 = 320000000, lab = "USAFRICOM \n Full Operational \n Capability")
 au_tick <- data.frame(x1 = as.Date("2013-07-01"), 
                        x2 = as.Date("2014-09-01"),
                        y1 = 310000000,
                        y2 = 335000000)
 au_label <- data.frame(x1 = as.Date("2015-01-01"), y1 = 358000000, lab = "Support to \n AMISOM in Somalia")
 un_tick <- data.frame(x1 = as.Date("2006-07-01"), 
                       x2 = as.Date("2005-04-01"),
                       y1 = 290000000,
                       y2 = 320000000)
  un_label <- data.frame(x1 = as.Date("2005-01-01"), y1 = 343000000, lab = "Support to \n UNAMID in Darfur")
 
aid_plot  <- aid_plot +
   geom_segment(aes(x = x1, y = y1, xend = x2, yend= y2), linetype= 2, 
                color = "grey12", size = 1, data = seg_tick) +
   geom_text(data = africom_label, aes(x = x1, y = y1, 
             xend = x1, yend = y1, label = lab, fontface = "bold"), size = 3.3, color = "grey12") +
   geom_segment(aes(x = x1, y = y1, xend = x2, yend= y2), linetype= 1, 
                color = "#666666", size = 1, data = au_tick) +
   geom_text(data = au_label, aes(x = x1, y = y1, 
                                       xend = x1, yend = y1, label = lab, fontface = "bold"), size = 3.3, color = "#666666") +
   geom_segment(aes(x = x1, y = y1, xend = x2, yend= y2), linetype= 1, 
                color = "#666666", size = 1, data = un_tick) +
   geom_text(data = un_label, aes(x = x1, y = y1, 
                                  xend = x1, yend = y1, label = lab, fontface = "bold"), size = 3.3, color = "#666666") 

# print DoD vs DoS aid plot
print(aid_plot) 

# Total Train & Equip obligations, FY2010-2019
t_e_cases<- as_tibble(t_e_cases)
t_e_cases %>%
  select(activity_name, constant_amount) %>%
  summarise(sum(constant_amount))



